11. Exercise: Add the VideosDatabase

L9 20 VideosDatabase SC

Now it’s your turn to complete this exercise yourself.

As a recap, you’ve already implemented VideoDao and it should look like this:

package com.example.android.devbyteviewer.database

import android.content.Context
import androidx.lifecycle.LiveData
import androidx.room.*

@Dao
interface VideoDao {
    @Query("select * from databasevideo")
    fun getVideos(): LiveData<List<DatabaseVideo>>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertAll(vararg videos: DatabaseVideo)
}



Your task now is to implement the VideosDatabase class in database/Room.kt.

1. Create the VideosDatabase class:

Create an abstract VideosDatabase class that extends RoomDatabase, and annotate it with @Database, including entities and version.

@Database(entities = [DatabaseVideo::class], version = 1)
abstract class VideosDatabase : RoomDatabase() {
}

2. Add the Dao:

Inside VideosDatabase, add an abstract videoDao variable.

abstract val videoDao: VideoDao

You’re doing a great job! The Room database is almost complete. Now let's use the singleton pattern to get an instance of the database.

3. Create a variable for you singleton:

In Room.kt, define an INSTANCE variable to store the singleton.

private lateinit var INSTANCE: VideosDatabase

4. Define a getDatabase() function to return the VideosDatabase:

fun getDatabase(context: Context): VideosDatabase { 
        return INSTANCE
}

5. Check whether the database has been initialized:

Inside getDatabase(), use ::INSTANCE.isInitialized to check if the variable has been initialized. If it hasn't, then initialize it.

if (!::INSTANCE.isInitialized) {
            INSTANCE = Room.databaseBuilder(context.applicationContext,
                    VideosDatabase::class.java,
                    "videos").build()
}

6. Make sure your code is synchronized so it’s thread safe:

Wrap the if-statement above with the following statement:

synchronized(VideosDatabase::class.java)

This is the last task to implement your Room database for offline caching. In the next section you’ll integrate this into the app using a repository!

If you want to start at this step, you can download this exercise code from: Step.04-Exercise-Add-VideosDatabase.

You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck go back and watch the video again.

Once you’re done, you can check your solution against the solution we’ve provided here Step.04-Solution-Add-VideosDatabase or using this git diff

Task Description:

Check the steps below as you implement them to complete this exercise

Task List:

Task Feedback:

Great work! You’ve implemented the room database and it’s ready to be used as an offline cache.

In the next section you’ll integrate this into the app using a repository!